/*
 * @Author: CPS
 * @Date: 2020-07-21 21:03:54
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-31 12:45:58
 * @Projectname Electron-fileWatcher
 * @Filename cmd.js
 */
'use strict'
import child_process from 'child_process'
import fs from 'fs'
import path from 'path'

let exec = {
  doc: "C:/Program Files (x86)/Microsoft Office/root/Office16/WINWORD.EXE",
  docx: "C:/Program Files (x86)/Microsoft Office/root/Office16/WINWORD.EXE",
  xls: 'C:/Program Files (x86)/Microsoft Office/root/Office16/EXCEL.EXE',
  xlsx: 'C:/Program Files (x86)/Microsoft Office/root/Office16/EXCEL.EXE',
  pdf: '',
  ppt: '',
  img: '',
  psd: '',
  cad: '',
}

function checkExec() {

}

let defaultSettings = {
  windowHide: false
}

function check(tarPath) {
  tarPath = path.resolve(tarPath)
}

function run(command, settings) {
  if (settings) Object.assign(defaultSettings, settings)

  console.log('执行命令' + command)
  child_process.exec(command, defaultSettings);
}

function openFolder(p) {
  if (fs.existsSync(path.resolve(p))) {
    run('start "" "' + p + '"')
  }
}

/*
 * 通过调用cmd 打开对应文件,如果给出exec,则使用exec打开对应的文件,否则系统使用系统默认
 *
 * @param      {string}  tar     The tar
 * @param      {string}  exec    The execute
 * @return     {<type>}  { description_of_the_return_value }
 */
function openFile(tar, exec = "") {
  if (!tar) return console.log('请输入要打开的文件路径')
  if (exec) {
    if (fs.existsSync(exec) && fs.existsSync(tar)) {
      run('"' + exec + '" "' + tar + '"')
    }
  } else {
    run(`start "" "${tar}"`)
  }
}

/*自动判断是否文件还是目录*/
function open(target, exec = "") {
  if (!fs.existsSync(target)) return console.log('文件不存在')

  if (fs.lstatSync(target).isFile()) {
    openFile(target, exec)
  } else {
    openFolder(target)
  }
}

export {
  open,
  openFolder,
  openFile
}

export default {
  open,
  openFolder,
  openFile
}
